﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using Server.API.Application.Command.Goods;

namespace Server.API.Application.Handler.Goods
{
    public class GoodsDelHandler:IRequestHandler<GoodsDelCommand,APIResult<int>>
    {
        private readonly IRepository<GoodsModel> goodsway;
        private readonly ILogger<GoodsDelHandler> log;
        private readonly IMapper mapper;

        public GoodsDelHandler(IRepository<GoodsModel> goodsway, ILogger<GoodsDelHandler> log , IMapper mapper)
        {
            this.goodsway = goodsway;
            this.log = log;
            this.mapper = mapper;
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="request">主键</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<int>> Handle(GoodsDelCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res=new APIResult<int>();
 
            var value  =await goodsway.GetValue(request.Id);
            if (value == null)
            {
                res.Num = StateCode.Fail;
                res.Message = "商品不存在";
                return res;
            }
            value.IsDel = true;
            var  result = await goodsway.Updateway(value);
            if(result > 0)
            {
                log.LogInformation("商品删除成功");

                res.Num = StateCode.OK;
                res.Message = "删除成功";
                res.Data = result;
            }
            else
            {
                log.LogError("商品删除失败");
                res.Num = StateCode.Fail;
                res.Message = "删除失败";
            }
            return res;
   
        }
    }
}
